"use strict";
/**
 * @class chat.common 聊天vue 组件
 */

define(['js/plugins/chat/chat.common.js', 'js/plugins/chatUtils/i18n/chatUtils.' + $E.lang, 'js/lib/vue.min'], function ($COMM, i18n, Vue) {
    var count = 20, limit = 0, chatServerHost, chatServerName,
        headImgBaseUrl = location.pathname.substring(0, location.pathname.indexOf('/', 1)) + '/fs/get?file=', clientid;
    var chatServerAddr = ''
        , currentVoiceAudio = null
        , showMessageByMessageType = false
        , tools = null
        , ajaxURL = "agentService.do"
        , Robot = $COMM.Robot
        , EMOTION = $COMM.EMOTION
        , ICONS = $COMM.ICONS
        , Tools = $COMM.Tools
        , REQUEST_STATUS = $COMM.REQUEST_STATUS
        , CHAT_REQUEST_TYPE = $COMM.CHAT_REQUEST_TYPE
        , USER_STATUS = $COMM.USER_STATUS
        , CLIENT_TYPE = $COMM.CLIENT_TYPE
        , NOTICE_TYPE = $COMM.NOTICE_TYPE
        , SoundManager = $COMM.SoundManager;


    var init = function (url, project) {
        $F.log("chatUtils-vue.component", '传递地址', url);
        chatServerAddr = url;
        if (chatServerAddr)
            chatServerHost = chatServerAddr.substring(0, chatServerAddr.lastIndexOf('/'));
        tools = new Tools(chatServerAddr);
        this.project = project;
        showMessageByMessageType = project.getParam('CHAHMT') === "1";
        Robot.init(project);
    };

    var WECHAT_MESSAGE_TYPE = {
        TEXT: "text",
        IMAGE: "image",
        REVOKE: "revoke",
        AGREE: "agree",
        DISAGREE: "disagree",
        MIXED: "mixed",
        VOICE: "voice",
        VIDEO: "video",
        CARD: "card",
        LOCATION: "location",
        EMOTION: "emotion",
        FILE: "file",
        LINK: "link",
        WEAPP: "weapp",
        CHATRECORD: "chatrecord",
        TODO: "todo",
        VOTE: "vote",
        REDPACKET: "redpacket",
        EXTERNAL_REDPACKET: "external_redpacket",
        MEETING: "meeting",
    };
    //调用服务接口
    var callService = function (url, data) {
        return tools.callService({
            url: tools.chatServerAddr + "/" + url,
            data: data
        });
    };

    var scrollToBottom = function (selector) {
        var target = $(selector, $('.chatsForuser'))[0];
        if (target) {
            target.scrollTop = target.scrollHeight;
        }
    }

    /**
     * 调用chat服务的ajax请求
     */
        // var viewForClient = Vue.extend({

        //     data: function(){
        //        return {
        //         sessionid: '',
        //         url: chatServerAddr + '/' + ajaxURL,
        //         name: 'chatTalkByClientId',
        //         clientId: clientid,
        //         qualityTest: ""
        //        }
        //     },
        //     methods: {
        //         loading: function (value) {
        //             this.clientId = '';
        //             this.clientId = value;
        //             $F.log('chatUtils -vmUserId - loading ', '修改client数据 ' + this.clientId);
        //         },
        //         loadSession: function (value) {
        //             this.sessionid = value;
        //             $F.log('chatUtils - loading Session', '修改session数据 ' + this.sessionid);
        //         },
        //         loadSessionForQualityTest: function (value) {
        //             this.sessionid = value;
        //             this.qualityTest = qualityTest;
        //             $F.log('chatUtils - loading Session', '修改session数据 ' + this.sessionid);
        //         }
        //     }
        // });

    var chatTalk = Vue.extend({
            props: ['token', 'ds', 'saveChat', 'prsession', 'clientid', 'serverUrl', 'qualityTest', 'heightLight', "markMessage"],
            template: `<div v-bind:class="{ 'messager-body': showMessageBody }" >
                    <div id="chatUtils-updateMessage" class="exDialog" style="display:none; padding: 5px;">
                        <div class="boxHeader">
                            <div class="topIcon"></div>
                            <div class="exTitle" v-text="i18n.exTitle"></div>
                        </div>
                        <a class="close_tip_icon" :title="i18n.closeTipIcon"><i class="far fa-times"></i></a>
                        <textarea rows="5" cols="100" class="chatUtils-updateMessage-textarea"></textarea>
                        <div class="btnsBar">
                            <button type="button" class="chrome js_submit" v-text="i18n.btnsBar.submit"></button>
                            <button type="button" class="chrome js_close" v-text="i18n.btnsBar.close"></button>
                        </div>
                    </div>
                    <div v-show="permBtn" class="queue-btn">
                        <div @click="changePerm(false)" class="common-queue" v-text="i18n.commonQueue"></div>
                        <div @click="changePerm(true)" class="perm-queue" v-text="i18n.permQueue"></div>
                    </div>
                    <p class="message_system" v-show="msgSize == 0 && markMessageData.length == 0" v-text="i18n.nohis"></p>
                    <div class="message_system  session-pre" @click="preSession" v-show="sessionPre && sessionPre != 0">{{i18n.prevSession.format(sessionPre)}}</div>
                    <div class="his-message"  v-for="msg in page.result" v-show ="isShowMessage(msg)">
                        <div v-if="msg.messageType == 100" class="message_system system-presession" >{{i18n.beforeSession.format(msg.text)}}</div>
                        <div v-else-if="msg.messageType == 99" class="message_system" v-html="msg.text"></div>
                        <div v-else-if="showMessageByMessageType && msg.messageType != 0 && msg.messageType != 1"
                         class="message_system message-auto" v-html="filterMsg((typeof msg.text=== 'undefined')? msg.message: msg.text, msg.userId, msg.id, msg.wechatMessageType|| '', msg.revokeFlag == 1)"></div>
                        <div v-else class="chat_view" v-show="filterMsg((typeof msg.text=== 'undefined')? msg.message: msg.text, msg.userId, msg.id, msg.wechatMessageType|| '', msg.revokeFlag == 1)" v-bind:class="filterHeight((typeof msg.text=== 'undefined')? msg.message: msg.text, msg.id, msg.userId)? 'height-div' : ''">
                            <div class="msg_container">
                                <div class="message" :class="msg.userType == 1 ? '' : 'me'"  v-bind:data-user="msg.userId">
                                    <img class="avatar" :src="filterHeadImage(msg.icon || msg.headImg , msg.userType)" class="avatar">
                                    <div class="content">
                                        <h4 class="nickname">{{filterShowName(msg.userName, msg.userId) + " " + new Date(msg.postTime).format("YYYY-MM-dd HH:mm:ss")}}</h4>
                                        <div v-on:click="editMessage($event, msg)" class="bubble js_message_bubble" :class="msg.userType ==  1 ? 'bubble_primary right' : 'bubble_default left' ">
                                            <div class="bubble_cont">
                                                <div class="plain">
                                                    <div class="revoked" v-show ="msg.revokeFlag == 1" v-text="i18n.revoke"></div>
                                                    <pre class="js_message_plain"  v-html="filterMsgWhithTranslate((typeof msg.text=== 'undefined')? msg.message: msg.text, msg.translateMessage, msg.userType, msg.userId, msg.id, msg.wechatMessageType|| '', msg.revokeFlag == 1)">
                                                    </pre>
                                                </div>
                                                <div class="plain message-translate" v-show="msg.translateMessage">
                                                    <pre class="js_message_plain"  
                                                        v-html="getTranslateMessage(msg.translateMessage || '', msg.text, msg.userType)"></pre>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="message-state" v-show="msg.userType != 1 && msg.messageState" >
                                            <div class="message-state-content message-state-accepted" v-if="msg.messageState == '0'" v-text="i18n.accepted"></div>
                                            <div class="message-state message-state-rejected" v-else-if="msg.messageState == '1'" v-text="i18n.rejected"></div>
                                            <div class="message-state message-state-delivered" v-else-if="msg.messageState == '2'" v-text="i18n.delivered"></div>
                                            <div class="message-state message-state-failed" v-else-if="msg.messageState == '3'" v-text="i18n.failed"></div>
                                            <div class="message-state message-state-read" v-else-if="msg.messageState == '4'" v-text="i18n.read"></div>
                                        </div>
                                    </div>
                                </div>
                                
                            </div>
                        </div>                           
                    </div>
                    <div class="mark-message"  v-for="(msg, index) in markMessageData">
                        <ul class="contexts-menu-list" v-bind:style="{top: y}" :class="msg.userType == 1 ? 'menu-you' : 'menu-me'" @mouseleave="leave()" 
                        v-show="canEdit && showEditForMsg != '' && showEditForMsg == msg.markGuid">
                            <li class="contexts-menu-item">
                               <button @click="editMessage()" style="float: left" class="toolsBtn" :alt="i18n.editMessage">
                               <i class="far fa-save pull-left"></i>{{i18n.editMessage}}</button>
                            </li>
                            <li class="contexts-menu-item">
                               <button @click="addCheckMessage()" style="float: left" class="toolsBtn" :alt="i18n.addMessage">
                               <i class="far fa-save pull-left"></i>{{i18n.addMessage}}</button>
                            </li>
                            <li class="contexts-menu-item">
                                <button @click="delCheckMessage()" style="float: left"  class="toolsBtn" :alt="i18n.deleteMessage">
                                <i class="fal fa-trash-alt"></i>{{i18n.deleteMessage}}</button>
                            </li>
                        </ul>
                        <div  @contextmenu.prevent="showContextmenu(msg, index, $event)" class="chat_view" v-bind:class="filterHeight((typeof msg.text=== 'undefined')? msg.message: msg.text, msg.chatMessageId, msg.userId)? 'height-div' : ''">
                            <div class="msg_container">
                                <div class="message" :class="msg.userType == 1 ? '' : 'me'"  v-bind:data-user="msg.userId">
                                    <img class="avatar" :src="filterHeadImage(msg.icon || msg.headImg , msg.userType)" class="avatar">
                                    <div class="content">
                                        <h4 class="nickname" v-text="filterShowName(msg.userName, msg.userId)"></h4>
                                        <div class="bubble js_message_bubble" :class="msg.userType ==  1 ? 'bubble_primary right' : 'bubble_default left' ">
                                            <div class="bubble_cont">
                                                <div class="plain">
                                                    <pre class="js_message_plain"  
                                                        v-html="filterMsg((typeof msg.text=== 'undefined')? msg.message: msg.text,  msg.userId, msg.chatMessageId, msg.wechatMessageType|| '', msg.revokeFlag == 1)"></pre>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>                           
                    </div>
                    <div class="message_system session-next" @click="nextSession" v-show="sessionNext && sessionNext != 0" >{{i18n.nextSession.format(sessionNext)}}</div>
                    <div class="back-top" @click="backThisSession" v-show="(sessionNext && sessionNext != 0) || (sessionPre && sessionPre != 0)" :title="i18n.goback">
                        <i class="fa fa-angle-double-up" aria-hidden="true">
                    </div>
                    <div v-show="sessionInfo">
                        <p class="message_system" v-show="sessionInfo && sessionInfo.closeBy" v-text="'关闭人: ' + sessionInfo.closeBy"></p>
                        <p class="message_system" v-show="sessionInfo && sessionInfo.startTime" v-text="i18n.startTime +': ' +new Date(sessionInfo.startTime).format('YYYY-MM-dd HH:mm:ss')"></p>
                        <p class="message_system" v-show="sessionInfo && sessionInfo.endTime" v-text="i18n.endTime + ': ' + new Date(sessionInfo.endTime).format('YYYY-MM-dd HH:mm:ss')"></p>
                        <div class="message_system" v-show="sessionInfo && (sessionInfo.ratingDesc || sessionInfo.ratingContent)">
                            <em v-show="sessionInfo && sessionInfo.ratingDesc" v-text="i18n.rate + ': ' + sessionInfo.ratingDesc"></em>
                            <em class="message_system" v-show="sessionInfo && sessionInfo.ratingContent" v-text="i18n.rateContent + ': ' + sessionInfo.ratingContent"></em>
                        </div>
                        <div v-show="saveChat && msgSize > 0" class="message_system" @click="fnSaveChat()" v-text="i18n.saveChat"></div>
                    </div>
                    <div class="footer" v-show="isShowBtnFn()">
                        <div class="footButtonContainer" style="display:block">
                            <a href="javascript:;" class="btn prevBtn" v-show="page.pageNo > 1" v-on:click="prePage" :title="i18n.prev" v-text="i18n.prev"></a>
                            <a href="javascript:;" class="btn nextBtn" v-show="page.pageNo < page.totalCount" v-on:click="nextPage" :title="i18n.next" v-text="i18n.next"></a>
                        </div>
                    </div>
                  </div>`,
            data: function () {
                return {
                    i18n: i18n.talk,
                    clientid: '',
                    name: this.talkName,
                    serverUrl: this.serverUrl,
                    qualityTest: '',
                    showMessageBody: false,
                    perm: false,
                    editmessagVal: "",
                    permBtn: false,
                    page: {},
                    canEdit: false,
                    showEditForMsg: 0,
                    x: '0',
                    y: '0',
                    showMessageByMessageType: showMessageByMessageType,
                    msgSize: 0,
                    pageSize: 10,
                    pageNo: 1,
                    saveChat: "",
                    heightLightKeyArr: [],
                    heightLightKey: "",
                    sessionInfo: {
                        "agentId": "",
                        "clientId": "",
                        "closeBy": "",
                        "endTime": 0,
                        "id": 0,
                        "lastIndexedMessageId": 0,
                        "permFlag": 0,
                        "queueId": 0,
                        "ratingContent": "",
                        "ratingDesc": "",
                        "startTime": 0
                    },
                    addMarkMessage: {
                        requestType: "addMarkMessage",
                        text: "",
                        order: 0,
                        markId: "",
                        markGuid: "",
                        sessionid: this.sessionid,
                        userId: "",
                        agentId: $E.staff.id
                    },
                    backPage: {},
                    sessionPre: 0,
                    sessionNext: 0,
                    markMessage: false,
                    markMessageData: [],
                    sessionid: 0
                };
            },
            watch: {
                token: {
                    handler: function (val, oldval) {
                        $F.log("chatUtils-vue.component", 'token = ', val);
                    },
                    deep: false//对象内部的属性监听，也叫深度监听
                },
                ds: {
                    handler: function (val, oldval) {
                        $F.log("chatUtils-vue.component", 'ds = ', val);
                    },
                    deep: false//对象内部的属性监听，也叫深度监听
                },
                saveChat: {
                    handler: function (val, oldval) {
                        $F.log("chatUtils-vue.component", 'saveChat = ' + val);
                    },
                    deep: false//对象内部的属性监听，也叫深度监听
                },
                heightLight: {
                    handler: function (val, oldval) {
                        $F.log("chatUtils-vue.component", 'heightLightKey = ', val);
                        this.heightLightKey = val;
                        if (val.indexOf(",") > 0) {
                            this.heightLightKeyArr = val.split(",");
                        }
                        this.loading();
                    },
                    deep: false//对象内部的属性监听，也叫深度监听
                },
                prsession: {
                    handler: function (val, oldval) {
                        $F.log("chatUtils-vue.component", '监听sessionid', val);
                        var self = this;
                        if (val != 0) {
                            self.sessionid = val;
                            self.pageNo = 1;
                            if (self.sessionid != 0) {
                                var sessionId = self.sessionid;
                                if (typeof sessionId == 'object') {
                                    self.canEdit = sessionId.canEdit;
                                    self.sessionid = sessionId.sessionId;
                                    this.loadMarkMessages();
                                } else {
                                    if (sessionId.length == 36) {
                                        this.loadMarkMessages();
                                    } else {
                                        this.loading();
                                    }
                                }
                            }
                        }
                    },
                    deep: false//对象内部的属性监听，也叫深度监听
                },
                clientid: {
                    handler: function (val, oldval) {
                        var self = this;
                        $F.log("chatUtils-vue.component", '监听 客户的id', val);
                        this.initData();
                        self.pageNo = 0;
                        if (val) {
                            this.clientid = val;
                            if (self.clientid) {
                                this.loading();
                            }
                        }
                    },
                    deep: false//对象内部的属性监听，也叫深度监听
                },
                serverUrl: {
                    handler: function (val, oldval) {
                        $F.log("chatUtils-vue.component", '监听 客户的serverUrl', val);
                        this.chatServerAddr = val;
                    },
                    deep: true//对象内部的属性监听，也叫深度监听
                },
                qualityTest: {
                    handler: function (val, oldval) {
                        $F.log("chatUtils-vue.component", '是否是质检界面', val);
//                    this.qualityTest = true;
//                    this.qualityTest = val;
                    },
                    deep: false//对象内部的属性监听，也叫深度监听
                }
            },
            mounted: function () {
                var self = this;
                self.$nextTick(function () {
                    self.loading();
                })
            },
            filters: {},
            updated: function () {
                $F.notify(i18n.talk.finishTask, 1);
                var target = $('.chat_view');
                //给图片添加点击事件 放大图片显示
                $('img:not(.avatar,.qqemoji,.standard-emoji,.location)', target).one('load', function () {
                    $(this).css("cursor", "pointer").on("click", function () {
                        Tools.showOriginImage(this, chatServerAddr, $('img:not(.avatar,.qqemoji,.standard-emoji,.location)', target));
                    });
                    Tools.autoResizeImage(300, 300, this);
                    if (!this.heightLightKey) {
                        scrollToBottom('.message_panel');
                    }
                });
                //给voice添加点击事件，播放语音
                $('div.message-voice', target).off().on('click', function () {
                    var $voice = $(this);
                    var url = $voice.attr('data-url');
                    if (url) {
                        if (currentVoiceAudio && !currentVoiceAudio.paused && !currentVoiceAudio.ended && 0 < currentVoiceAudio.currentTime) {
                            currentVoiceAudio.pause();
                            currentVoiceAudio.currentTime = 0;
                            $voice.removeClass('active');
                            return;
                        }
                        if (!$voice.hasClass('listened')) {
                            $voice.addClass('listened');
                        }
                        if (!url.startsWith('http'))
                            url = chatServerHost + url;
                        currentVoiceAudio = new Audio(url);
                        $(currentVoiceAudio).on('play', function () {
                            $voice.addClass('active');
                        }).on('ended', function () {
                            $voice.removeClass('active');
                        }).on('error', function () {
                            $voice.removeClass('active');
                        });
                        currentVoiceAudio.play();
                    }
                });
                $('div.message-file', target).off().on('click', function () {
                    var $file = $(this);
                    var url = $file.attr('data-url');
                    if (url) {
                        if (!url.toLowerCase().startsWith("http")) {
                            url = chatServerHost + url;
                        }
                        window.open(url, 'FILE_DOWNLOAD');
                    }
                });
                $('div.message-location', target).off().on('click', function () {
                    var $location = $(this);
                    var latitude = $location.attr('data-latitude'),
                        longitude = $location.attr('data-longitude'),
                        label = $location.attr('data-address'),
                        map = $location.attr('data-map'),
                        mapUrl = 'aMaps.html';
                    if (map === 'baidu') {
                        mapUrl = 'baiduMaps.html';
                    } else if (map === 'tencent') {
                        mapUrl = 'tencentMaps.html';
                    }
                    window.open(mapUrl + '?latitude=' + latitude + '&longitude=' + longitude + '&label=' + label, '_blank');
                });

                $('.message', target).each(function (i, msg) {
                    var userId = $(this).attr('data-user'),
                        agentId = $(this).attr('data-agentId'),
                        clientId = $(this).attr('data-clientId'),
                        from = $(this).attr('data-clientFrom'),
                        sessionId = $(this).attr('data-session');
                    $('.avatar', this).off().on('error', function () {
                        var avatar;
                        if (userId === agentId) {
                            avatar = ICONS.AGENT.ELITE;
                        } else if (userId === clientId) {
                            if ($F.equalsIgnoreCase(from, 'APP')) {
                                avatar = ICONS.CLIENT.PHONE;
                            } else if ($F.equalsIgnoreCase(from, 'MOBILE')) {
                                avatar = ICONS.CLIENT.PHONE;
                            } else if ($F.equalsIgnoreCase(from, 'WECHAT')) {
                                avatar = ICONS.CLIENT.WECHAT;
                            } else {
                                avatar = ICONS.CLIENT.PC;
                            }
                        } else {
                            avatar = ICONS.AGENT.OTHER_AGENT;
                        }
                        $(this).attr('src', avatar);
                    });
                });
                if (this.heightLightKey) {
                    $(".hisMain").scrollTop(0);
                    var times = 0;
                    var scrollTimes = setInterval(function () {
                        if (times >= 5) {
                            clearInterval(scrollTimes);
                        }
                        times++;
                        $F.log("chat-uitl", "调整滚动条")
                        var heightDiv = $('.height-div');
                        if (heightDiv && heightDiv.position()) {
                            var top = heightDiv.position().top;
                            var iDiv = 0;
                            if (top > 10) {
                                var height = 0;
                                $.each($(".messager-body"), function (i, ht) {
                                    if ($(ht).height() > height) {
                                        height = $(ht).height();
                                        iDiv = i;
                                    }
                                });
                                var scrollHeight = height - $($(".hisMain")[iDiv]).scrollTop() - $(".hisMain").height();
                                if (scrollHeight < 10) {
                                    clearInterval(scrollTimes);
                                } else {
                                    $($(".hisMain")[iDiv]).scrollTop(heightDiv.position().top);
                                    $('.talkDialog').scrollTop(heightDiv.position().top);
                                    clearInterval(scrollTimes);
                                }
                            } else if (top < 0) {
                                $($(".hisMain")[iDiv]).scrollTop(heightDiv.position().top);
                                $('.talkDialog').scrollTop(heightDiv.position().top);
                                clearInterval(scrollTimes);
                            } else {
                                clearInterval(scrollTimes);
                            }
                        } else {
                            clearInterval(scrollTimes);
                        }
                    }, 100);
                }

            },
            methods: {
                initData: function () {
                    this.sessionid = 0;
                },
                loadMarkMessages: function () {
                    var self = this;
                    if (self.sessionid) {
                        callService(ajaxURL, {
                            requestType: 'getMarkMessage',
                            markid: self.sessionid,
                            agentId: $E.staff.id,
                            token: this.token
                        }).done(function (data) {
                            $F.log("chatUtils-vue.component", "loadMarkMessages data for chat—talk", data);
                            if (data.status == 'success') {
                                self.markMessageData = data.msgs;
                            } else {
                                $F.log("chatUtils-vue.component", '请求失败');
                            }
                        });
                    }
                },
                focusContext: function (msg) {
                    this.addMarkMessage.text = msg.text;
                    this.addMarkMessage.order = msg.orders;
                    this.addMarkMessage.markId = msg.markId;
                    this.addMarkMessage.userId = msg.userId;
                    this.addMarkMessage.markGuid = msg.markGuid;
                    this.addMarkMessage.sessionid = msg.chatSessionId;
                },

                showContextmenu: function (msg, index, e) {
                    if (this.canEdit) {
                        if (index > 4)
                            this.y = (0 - $('.contexts-menu-list').height()) + 'px';
                        else
                            this.y = 0;
                        $F.log("chatUtils-vue.component", 'mouse 右键菜单' + e.offsetX + '/' + e.offsetY + '[' + this.x + '/' + this.y + ']' + JSON.stringify(msg));
                        this.x = e.offsetX;
                        this.showEditForMsg = msg.markGuid;
                        this.addMarkMessage.text = msg.text;
                        this.addMarkMessage.order = msg.orders;
                        this.addMarkMessage.markId = msg.markId;
                        this.addMarkMessage.userId = msg.userId;
                        this.addMarkMessage.markGuid = msg.markGuid;
                        this.addMarkMessage.sessionid = msg.chatSessionId;
                    }
                },
                addCheckMessage: function () {
                    var self = this;
                    if (self.canEdit) {
                        H5Utils.input({
                            title: i18n.talk.addMessageTitle,
                            value: '',
                            onSubmit: function (e) {
                                e = e.trim();
                                if (!e)
                                    return false;
                                self.addMarkMessage.text = e;
                                $F.log("chatUtils-vue.component", '增加一条数据,showEditForMsg[' + this.showEditForMsg + "]");
                                //requestType=addMarkMessage&text=消费内容&order=10&sessionid=13727&markId=95b07914-9750-4108-8933-b4f3cad0efb9&userId=ZFXKSA&agentId=******
                                callService(ajaxURL, self.addMarkMessage).done(function (data) {
                                    $F.log("chatUtils-vue.component", "addCheckMessage data for chat—talk", data);
                                    self.showMarkMessage(data);
                                });
                                return true;
                            }
                        });

                    }
                },
                delCheckMessage: function () {
                    if (this.canEdit) {
                        var self = this;
                        $F.log("chatUtils-vue.component", '删除一条数据,showEditForMsg[' + this.showEditForMsg + "]");
                        $F.confirm(i18n.talk.sureToDelete, function () {
                            callService(ajaxURL, {
                                requestType: "delMarkMessage",
                                markId: self.addMarkMessage.markId,
                                id: self.addMarkMessage.markGuid,
                                agentId: $E.staff.id,
                                userId: self.addMarkMessage.userId,
                                text: self.addMarkMessage.text,
                                token: this.token
                            }).done(function (data) {
                                $F.log("chatUtils-vue.component", "delCheckMessage data for chat—talk", data);
                                self.showMarkMessage(data);
                            });
                        })

                    }
                },
                leave: function (msg) {
                    if (this.canEdit) {
                        this.showEditForMsg = '';
                        // $F.log("chatUtils-vue.component", 'mouse leave:', JSON.stringify(msg));
                    }
                },
                showMarkMessage: function (data) {
                    if (data.status == 'success') {
                        var self = this;
                        self.markMessageData = data.msgs;
                    } else {
                        $F.alert(data.msgs);
                    }

                },
                updateMarkMessage: function () {
                    var self = this;
                    var addMarkMessage = self.addMarkMessage;
                    if (addMarkMessage.text) {
                        $F.log("chatUtils-vue.component", 'update mark message:', JSON.stringify(addMarkMessage) + ', ' + this.showEditForMsg);
                        callService(ajaxURL, {
                            requestType: 'editMarkMessage',
                            markId: addMarkMessage.markId,
                            id: addMarkMessage.markGuid,
                            agentId: $E.staff.id,
                            userId: addMarkMessage.userId,
                            text: addMarkMessage.text,
                            token: this.token
                        }).done(function (data) {
                            $F.log("chatUtils-vue.component", "update mark message", data);
                            if (data.status == 'success') {
                                $F.log("chatUtils-vue.component", '请求success');
                                $F.info(i18n.talk.successUpdate);
                                self.loadMarkMessages();
                            } else {
                                $F.log("chatUtils-vue.component", '请求失败');
                            }
                        });
                    }
                },
                loading: function (flag) {
                    var self = this;
                    $F.log("chatUtils-vue.component", "loading", "sessionid = " + self.sessionid + " clientId = " + self.clientid);
                    if (self.sessionid || self.clientid) {
                        var sessionidPost = self.sessionid;
                        if (flag) {
                            if (flag == 'pre') {
                                sessionidPost = self.sessionPre
                            } else if (flag = 'next') {
                                sessionidPost = self.sessionNext
                            }
                        }
                        callService(ajaxURL, {
                            requestType: 'hisMessageForPage',
                            sessionid: sessionidPost,
                            epid: $E.staff.epid,
                            clientid: self.clientid,
                            permFlag: self.perm,
                            pageSize: self.pageSize,
                            pageNo: self.pageNo,
                            token: this.token
                        }).done(function (data) {
                            self.showMessageBody = true;
                            $F.log("chatUtils-vue.component", "loading data for chat—talk", data);
                            if (data.status == 'success') {
                                if (data.page) {
                                    var page = data.page;
                                    if (flag) {
                                        var resultInfoNew = data.page.result;
                                        var resultInfoOld = self.page.result;
                                        if (flag == 'pre') {
                                            if (resultInfoOld.length > 0) {
                                                resultInfoNew.push({
                                                    "messageType": 100,
                                                    "text": self.sessionPre,
                                                });
                                            }
                                            $.each(resultInfoOld, function (i, info) {
                                                resultInfoNew.push(info);
                                            })
                                            self.page.result = resultInfoNew;
                                        } else if (flag == 'next') {
                                            if (resultInfoNew.length > 0) {
                                                resultInfoOld.push({
                                                    "messageType": 99,
                                                    "text": self.sessionNext,
                                                });
                                            }
                                            $.each(resultInfoNew, function (i, info) {
                                                resultInfoOld.push(info);
                                            })
                                            self.page.result = resultInfoOld;
                                        }
                                    } else {
                                        self.page = page;
                                    }

                                    if (page && page.mark) {
                                        var mark = page.mark;
                                        if (flag) {
                                            if (flag === 'pre') {
                                                if (mark && mark.sessionPre) {
                                                    self.sessionPre = mark.sessionPre;
                                                } else {
                                                    self.sessionPre = 0;
                                                }
                                            } else if (flag === 'next') {
                                                if (mark && mark.sessionNext) {
                                                    self.sessionNext = mark.sessionNext;
                                                } else {
                                                    self.sessionNext = 0;
                                                }
                                            }
                                        } else {
                                            if (mark && mark.sessionPre) {
                                                self.sessionPre = mark.sessionPre;
                                            }
                                            if (mark && mark.sessionNext) {
                                                self.sessionNext = mark.sessionNext;
                                            }
                                        }
                                    }
                                    if (self.page && self.page.result) {
                                        var result = self.page.result;
                                        self.msgSize = result.length;
                                        self.pageNo = page.pageNo;
                                    }
                                }
                                if (page && page.mark && page.mark.sessionInfo) {
                                    self.sessionInfo = page.mark.sessionInfo;
                                } else {
                                    self.sessionInfo.startTime = 0;
                                    self.sessionInfo.endTime = 0;
                                }
                                self.permBtn = data.perm;
                            } else {
                                $F.log("chatUtils-vue.component", '请求失败');
                            }
                        });
                    }
                },
                preSession: function () {
                    var self = this;
                    // $F.info("加载会话[" + self.sessionPre + "]");
                    self.loading('pre');

                },
                nextSession: function () {
                    var self = this;
                    // $F.info("加载会话[" + self.sessionNext + "]");
                    self.loading('next');
                },

                backThisSession: function () {
                    var $systemPresession = $(".system-presession").last(0).parent();
                    var $talkDialog = $(".messager-body").parent();
                    if ($systemPresession && $systemPresession.offset()) {
                        var topControl = function () {
                            return ($systemPresession.offset().top + $systemPresession.outerHeight() - $talkDialog.offset().top);
                        }
                        if (topControl() != 0) {
                            $talkDialog.scrollTop(0);
                            var top = topControl();
                            $talkDialog.scrollTop(top);
                        }
                    } else {
                        $talkDialog.scrollTop(0);
                    }
                },

                fnSaveChat: function () {
                    var self = this;
                    window.open(chatServerAddr + '/naSaveOrPrintChat.do?action=save&sessionId=' + this.sessionid, '保存聊天历史', 'left=300, top=150, width=420, height=420, menubar=no, toolbar=no, titlebar=no, directories=no, location=no, scrollbars=no, resizable=yes, status=no');
                },
                editmessageForGetVal: function (e) {
                    this.editmessagVal = e.target.textContent;
                },
                editMessage: function (e) {
                    // this.addMarkMessage.text = msg.text;
                    // this.addMarkMessage.order = msg.orders;
                    // this.addMarkMessage.markId = msg.markId;
                    // this.addMarkMessage.userId = msg.userId;
                    // this.addMarkMessage.markGuid = msg.markGuid;
                    // this.addMarkMessage.sessionid = msg.chatSessionId;
                    var self = this;
                    if (self.canEdit) {
                        var selfMsg = self.addMarkMessage;
                        $F.log("chatUtils-vue.component", 'editMessage befor edite:', selfMsg);
                        $F.dialogOpen($("#chatUtils-updateMessage"), {
                            onOpen: function () {
                                $(".chatUtils-updateMessage-textarea", this).val(selfMsg.text);
                            },
                            onSubmit: function (close) {
                                var modifyMsg = $(".chatUtils-updateMessage-textarea", this).val();
                                $F.log("vue.component.chat", "editMessage after edite:", modifyMsg);
                                if (modifyMsg != selfMsg.text) {
                                    var flag = false;
                                    $.each(self.markMessageData, function (i, markMessage) {
                                        if (markMessage.markGuid === selfMsg.markGuid) {
                                            flag = true;
                                            self.addMarkMessage.text = modifyMsg;
                                            markMessage.messageText = modifyMsg,
                                                markMessage.messageType = selfMsg.messageType,
                                                markMessage.modifyTime = new Date().getTime()
                                            self.$forceUpdate();
                                        }
                                    })
                                    if (flag) {
                                        self.updateMarkMessage();
                                    }
                                }
                                if (close)
                                    close();
                            }
                        });
                    }
                },
                changePerm: function (value) {
                    this.perm = value;
                    this.clientid = this.clientid;
                    this.messageId = 0;
                    this.loading();
                },
                isShowBtnFn: function () {
                    return true;
                },
                showCloseBy: function (msg) {
                    return "";
                },
                filterHeadImage: function (headImg, useType) {
                    var self = this;
                    if (headImg) {
                        if (headImg.startsWith('headimg') || headImg.startsWith('/headimg')) {
                            return headImgBaseUrl + headImg
                        } else if (headImg.startWith('livebot/getIcon.do')) {
                            headImg = chatServerAddr + "/" + headImg;
                        }
                        return headImg;
                    } else if (useType == 1) {
                        return ICONS.CLIENT.PC;
                    } else {
                        return ICONS.AGENT.ELITE;
                    }
                },

                filterShowName: function (userName, userId) {
                    if (userName) {
                        return userName;
                    } else {
                        if (userId.length == 6) {
                            return userId;
                        } else {
                            return i18n.talk.anonymous;
                        }
                    }
                },
                //上一页点击触发
                prePage: function () {
                    $F.log("chatUtils-vue.component", 'prepage');
                    var self = this;
                    if (self.pageNo > 1) {
                        self.pageNo = self.pageNo - 1;
                        self.loading();
                    }

                },
                //下一页点击触发
                nextPage: function () {
                    $F.log("chatUtils-vue.component", 'nextPage');
                    var self = this;
                    if (self.pageNo < self.page.totalCount) {
                        self.pageNo = self.pageNo + 1;
                        self.loading();
                    }
                },
                setDataForPage: function (data) {
                    var messages = data.page.result;
                },
                isAgent: function (msg) {
                    if (msg.agentId == "") {
                        return false;
                    } else {
                        return true;
                    }
                },
                isShowMessage: function (msg) {
                    if (msg) {
                        if (typeof msg.text === 'undefined') {
                            if (typeof msg.message === 'undefined') {
                                return false;
                            } else {
                                return true;
                            }
                        } else {
                            if (msg.text) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    } else {
                        return false;
                    }
                },

                filterHeight: function (msgText, id, userId) {
                    if (msgText == "") false;
                    msgText = this.filterMessage(msgText, userId);
                    //添加高亮
                    if (this.heightLightKey) {
                        if (this.heightLightKeyArr.length > 0) {
                            if ($.inArray(id + '', this.heightLightKeyArr) > -1) {
                                return true;
                            } else {
                                return false;
                            }
                        } else {
                            if (this.heightLightKey && msgText.indexOf(this.heightLightKey) > -1) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    } else {
                        return false;
                    }
                },

                getTranslateMessage(msgText, translateMessage, userType, userId, id, wechatMessageType, revokeFlag) {
                    return userType == 1 ? (i18n.talk.translate + EMOTION.filterEmojis(msgText)) : (i18n.talk.original + EMOTION.filterEmojis(translateMessage));
                },

                filterMsgWhithTranslate: function (msgText, translateMessage, userType, userId, id, wechatMessageType, revokeFlag) {
                    let text = this.filterMsg(msgText, userId, id, wechatMessageType, revokeFlag);
                    if (userType == 1) {
                        return text;
                    } else {
                        if (translateMessage) {
                            return translateMessage;
                        } else {
                            return text;
                        }
                    }
                },

                filterMsg: function (msgText, userId, id, wechatMessageType, revokeFlag) {
                    var self = this;
                    if (msgText == "") false;
                    if (!wechatMessageType) {
                        msgText = this.filterMessage(msgText, userId);
                    } else {
                        var msgTestJSON = JSON.parse(msgText);
                        switch (wechatMessageType) {
                            case WECHAT_MESSAGE_TYPE.TEXT:
                                msgText = msgTestJSON.content;
                                break;
                            case WECHAT_MESSAGE_TYPE.IMAGE: //TODO
                                msgText = '<div class="message-image" data-fileSize="' + msgTestJSON.fileSize + '"></div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.REVOKE:
                                msgText = '<div class="message-revoke" data-msgid="' + msgTestJSON.pre_msgid + '"></div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.AGREE:
                                msgText = '<div class="message-agree" data-userid="' + msgTestJSON.userid + '" data-time="' + msgTestJSON.agreeTime + '"></div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.MIXED:
                                msgText = '<div class="message-agree" data-userid="' + msgTestJSON.userid + '" data-time="' + msgTestJSON.agreeTime + '"></div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.DISAGREE:
                                msgText = '<div class="message-agree" data-userid="' + msgTestJSON.userid + '" data-time="' + msgTestJSON.agreeTime + '"></div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.VOICE:
                                msgText = '<div class="message-voice" data-size="' + msgTestJSON.voiceSize + '" data-length="' + msgTestJSON.playLength + '"></div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.VIDEO:
                                msgText = '<div class="message-video" data-size="' + msgTestJSON.filesize + '" data-length="' + msgTestJSON.playLength + '"></div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.CARD:
                                msgText = '<div class="message-card" data-corpname="' + msgTestJSON.corpname + '" data-userid="' + msgTestJSON.userid + '">' +
                                    '<span class="title">' + msgTestJSON.corpname + '</span>' +
                                    '<span class="desc">' + msgTestJSON.userid + '</span>' +
                                    '</div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.LOCATION:
                                msgText = '<div class="message-location" ' +
                                    'data-latitude="' + msgTestJSON.latitude + '" ' +
                                    'data-longitude="' + msgTestJSON.longitude + '" ' +
                                    'data-address="' + msgTestJSON.address + '">' +
                                    '</div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.EMOTION:
                                msgText = '<div class="message-emotion" ' +
                                    'data-type="' + msgTestJSON.type + '" ' +
                                    'data-width="' + msgTestJSON.width + '" ' +
                                    'data-height="' + msgTestJSON.height + '" ' +
                                    'data-imageSize="' + msgTestJSON.imageSize + '">' +
                                    '</div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.FILE:
                                msgText = '<div class="message-file" ' +
                                    'data-fileName="' + msgTestJSON.fileName + '" ' +
                                    'data-fileExt="' + msgTestJSON.fileExt + '" ' +
                                    'data-fileSize="' + msgTestJSON.fileSize + '">' +
                                    '</div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.LINK:
                                msgText = '<a href="' + msgTestJSON.linkUrl + '" class="message-link" target="_blank">' +
                                    '<span class="title">' + msgTestJSON.fileName + '</span>' +
                                    '<span class="desc">' + msgTestJSON.description + '</span>' +
                                    '<img src="' + msgTestJSON.imageUrl + '">' +
                                    '</a>';
                                break;
                            case WECHAT_MESSAGE_TYPE.WEAPP:
                                msgText = '<div class="message-weapp" ' +
                                    'data-title="' + msgTestJSON.title + '" ' +
                                    'data-description="' + msgTestJSON.description + '" ' +
                                    'data-userName="' + msgTestJSON.userName + '" ' +
                                    'data-displayName="' + msgTestJSON.displayName + '">' +
                                    '<span class="tip">' + msgTestJSON.displayName + '</span>' +
                                    '<span class="title">' + msgTestJSON.title + '</span>' +
                                    '<span class="description">' + msgTestJSON.description + '</span>' +
                                    '<span class="userName">' + msgTestJSON.userName + '</span>' +
                                    '</div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.CHATRECORD:
                                msgText = '<div class="message-chatrecord" ' +
                                    'data-title="' + msgTestJSON.title + '" ' +
                                    'data-description="' + msgTestJSON.description + '" ' +
                                    'data-userName="' + msgTestJSON.userName + '" ' +
                                    'data-displayName="' + msgTestJSON.displayName +
                                    '">' +
                                    '<span class="title">' + msgTestJSON.title + '</span>' +
                                    '<ul>' +
                                    '<li class="item">' +
                                    '<span class="name"></span>' +
                                    '<span class="content"></span>' +
                                    '</li>' +
                                    '<li class="item">' +
                                    '<span class="name"></span>' +
                                    '<span class="content"></span>' +
                                    '</li>' +
                                    '</ul>' +
                                    '</div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.TODO:
                                msgText = '<div class="message-todo" ' +
                                    'data-title="' + msgTestJSON.title + '" ' +
                                    'data-content="' + msgTestJSON.content + '" ' +
                                    '">' +
                                    '<span class="title">' + msgTestJSON.title + '</span>' +
                                    '<span class="desc">' + msgTestJSON.content + '</span>' +
                                    '</div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.VOTE:
                                msgText = '<div class="message-vote" ' +
                                    'data-voteTitle="' + msgTestJSON.voteTitle + '" ' +
                                    'data-voteItem="' + msgTestJSON.voteItem + '" ' +
                                    'data-voteType="' + msgTestJSON.voteType + '" ' +
                                    'data-voteId="' + msgTestJSON.voteId +
                                    '">' +
                                    '</div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.REDPACKET:
                                msgText = '<div class="message-repeacket" ' +
                                    'data-type="' + msgTestJSON.type + '" ' +
                                    'data-wish="' + (msgTestJSON.wish || msgTestJSON.pkWish) + '" ' +
                                    'data-totalcnt="' + (msgTestJSON.totalcnt || msgTestJSON.pkTotalCnt) + '" ' +
                                    'data-totalamount="' + (msgTestJSON.totalamount || msgTestJSON.pkTotalAmount) +
                                    '">' +
                                    '<span class="wish">' + (msgTestJSON.wish || msgTestJSON.pkWish) + '</span>' +
                                    '<span class="type">' + (msgTestJSON.totalcnt || msgTestJSON.pkTotalCnt) + '</span>' +
                                    '</div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.EXTERNAL_REDPACKET:
                                msgText = '<div class="message-repeacket" ' +
                                    'data-type="' + msgTestJSON.type + '" ' +
                                    'data-wish="' + msgTestJSON.pkWish + '" ' +
                                    'data-totalcnt="' + msgTestJSON.pkTotalCnt + '" ' +
                                    'data-totalamount="' + msgTestJSON.pkTotalAmount +
                                    '">' +
                                    '<span class="wish">' + msgTestJSON.wish + '</span>' +
                                    '</div>';
                                break;
                            case WECHAT_MESSAGE_TYPE.MEETING:
                                msgText = '<div class="message-metting" ' +
                                    'data-topic="' + msgTestJSON.topic + '" ' +
                                    'data-address="' + msgTestJSON.address + '" ' +
                                    'data-remarks="' + msgTestJSON.remarks + '" ' +
                                    'data-meetingid="' + msgTestJSON.meetingid + '" ' +
                                    'data-meetingType="' + msgTestJSON.meetingType + '" ' +
                                    'data-status="' + msgTestJSON.status +
                                    '">' +
                                    '<span class="tip">' + msgTestJSON.topic + '</span>' +
                                    '<span class="title">' + msgTestJSON.address + '</span>' +
                                    '<span class="desc">' + msgTestJSON.remarks + '</span>' +
                                    '<span class="desc">' + msgTestJSON.meetingid + '</span>' +
                                    '<span class="desc">' + msgTestJSON.meetingType + '</span>' +
                                    '</div>';
                                break;
                        }
                    }

                    $F.log("chatUtils-vue.component", userId + "发送聊天内容", msgText);
                    //添加高亮
                    if (this.heightLightKey) {
                        if (this.heightLightKeyArr.length > 0) {
                            if ($.inArray(id + '', this.heightLightKeyArr) > -1) {
                                msgText = "<span style=\"background-color: #ff0; display: inline-block;\">" + msgText + "</span>";
                            }
                        } else {
                            msgText = msgText.replaceAll(this.heightLightKey, "<span style=\"background-color: #ff0; display: inline;\">" + this.heightLightKey + "</span>");
                        }
                    }
                    // msgText = msgText + (revokeFlag? '<span class="revoke">撤回</span>': '');
                    return msgText;
                },
                filterMessage: function (msgText, userId) {
                    if (Robot.isRobot(userId)) {
                        if (typeof msgText == 'string') {
                            try {
                                msgText = Robot.parseRobotMessage(msgText, userId);
                            } catch (e) {
                                $F.err(e)
                            }
                        }
                    } else {
                        //解析某种格式化消息
                        // msgText = Tools.parseHtmlEntity(msgText);
                        msgText = Tools.parseFormattedMsg(msgText);
                        msgText = tools.parseDisplayContent(msgText);
                    }
                    if (!msgText) return '';
                    //过滤表情字符串，把[表情]转换成表情对应的img标签
                    if (msgText && typeof msgText == 'string') {
                        msgText = EMOTION.filterEmojis(msgText);
                    }
                    if (!Robot.isRobot(userId)) {
                        if (msgText && typeof msgText == 'object') {
                            if (msgText.picUrl) {
                                var imgUrlFromWechat = msgText.picUrl;
                                msgText = '<img src="' + imgUrlFromWechat + '">';
                            }
                        }
                        //把url字符串包装成a标签的连接

                        msgText = Tools.wrapURL(msgText);
                        msgText = tools.parseContent(msgText);
                    }
                    var target = $('<div>').append(msgText);
                    $('video', target).each(function (i, video) {
                        var $video = $(video), src = $video.attr("src");
                        if (!src.toLowerCase().startsWith('http')) {
                            src = chatServerHost + src;
                        }
                        $video.attr('src', src).css('width', 300);
                        $F.log("chatUtils-vue.component", userId + "发送聊天内容", $video.innerHTML);
                    });
                    return target.html();
                }
            }
        });

    return {
        CHATTALK: chatTalk,
        init: init
    }
});